package com.back.filter;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.http.ContentType;
import com.back.excepction.BaseException;
import com.back.model.reslut.Result;
import com.back.utils.JacksonUtils;
import com.back.utils.Redisutils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.BindException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Order(1)
// @Component
public class WebVisitFilter implements Filter {


    @Resource
    private Redisutils redisutils;

    final private List<String> list = Arrays.asList("/user/login","/user/register","/pas");

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String requestURI = httpServletRequest.getRequestURI();
        if (isExcluded(requestURI)){
            filterChain.doFilter(servletRequest, servletResponse);
        }else {
            System.out.println("拦截起执行了-----");
            //是否已登录
            if (StpUtil.isLogin()){
                filterChain.doFilter(servletRequest, servletResponse);
            }else {
                HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
                httpServletResponse.setContentType("application/json; charset=UTF-8");
                String res = JacksonUtils.objectToJson( Result.faile(503,"未登录"));
                httpServletResponse.getWriter().write(res);

            }
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }

    private boolean isExcluded(String requestURI) {
        // 简单实现：检查请求路径是否包含排除路径
        // 更复杂的匹配可以用正则表达式或 Ant 风格路径匹配
        return list.stream().anyMatch(requestURI::startsWith);
    }

}
